import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Сляб катаный'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up = None
        try:
            product = row["Первичный продукт"]
            thickness=row["Толщина раската, мм <Производство>"]
            steel_mark = row["Марка стали <Производство>"]
            strength_class = consolidator.strength_by_steel(steel_mark)
            strength_2 = consolidator.strength_mapping(strength_class,steel_mark)
            strength_led = consolidator.strength_led(strength_2[0])
            strength_led_int = int(strength_led[1:])
            gmsps = consolidator.get_gmsps(steel_mark,"ТОЛСТЫЙ СЛЯБ")
            print(f"{product} - strength_led: {strength_led}; gmsps: {gmsps}; strength_led_int: {strength_led_int}")
            product_up=f"{product} {strength_led}"
            if "ГУ" in gmsps: product_up=f"{product} ГУ"
            elif strength_led_int >=60:
                thickness_led = consolidator.nearest_in_guid("Параметры по Продукту Прокат",
                f"`Производство`=='Сляб катаный' and `Продукт`=='{product}' and `Доп параметр2`=='{strength_led}'",
                "Доп параметр1",thickness,"Доп параметр1")
                thickness_led_s = str(thickness_led).replace(".0","")
                product_up=f"{product} Т{thickness_led_s} {strength_led}"
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__slab_rolled__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

